<?php
/**
 * Created by 王跃达.
 * User: 小马出行
 * Date: 2017/8/24
 * Time: 16:17
 */
namespace app\inter\logic;

use app\api\model\PassengerModel;
use app\api\model\PayLogModel;
use app\inter\model\LocalModel;
use app\inter\model\OrderCommonModel;
use my\Address;
use my\Tools;
use think\Cache;
use think\Db;
use think\Model;

class TripLogic extends Model
{

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 更新订单支付日志
     * @param $map
     * @param $data
     * @return string|false
     * */
    public function renewPayLog($map,$data)
    {
        $car_model = new PayLogModel();
        return $car_model->updatePayLog($map,$data);
    }

    /**
     * 将订单的轨迹存入缓存
     * @param $did
     * @param $local//APP传来的坐标
     * @param $cache//订单和司机关系记录缓存，形式为array('common_id1'=>'order_status1','common_id2'=>'order_status2',...)
    */
    public function localCache($did,$local,$cache)
    {
        //$data_local需要存入缓存的数据
        //$order_local_cache从缓存中获取的数据
        $data_local['driver_id'] = $did;
        $data_local['longitude'] = $local['car_lng'];
        $data_local['latitude'] = $local['car_lat'];
        $data_local['direction'] = $local['direction'];
        $data_local['speed'] = $local['speed'];
        $data_local['created_time'] = time();
        foreach ($cache as $key => $val){
            $data_local['common_id'] = $key;//键为订单id
            switch ($val){
                //已经派单
                case '35':
                    $data_local['status'] = 1;
                    break;
                //行程中
                case '40':
                    $data_local['status'] = 2;
                    break;
                default:
                    $data_local['status'] = null;
                    break;
            }
            $data_local['distance'] = 0;
            /*$order_local_cache形式为array(0=>array('driver_id'=>1,'distance'=>0,....),1=>array('driver_id'=>2,'distance'=>1,....),....)*/
            $order_local_cache = Cache::get('order_local_'.$key);//common_id对应订单的轨迹日志
            if(empty($order_local_cache)){
                $order_local_cache = array(0=>$data_local);
            }
            else{
                $index = count($order_local_cache)-1;
                $data_local['distance'] =
                    Address::GetDistance($order_local_cache[$index]['latitude'],$order_local_cache[$index]['longitude']
                        ,$local['car_lat'],$local['car_lng']);
                array_push($order_local_cache,$data_local);
            }
            Cache::set('order_local_'.$key,$order_local_cache,0);
            unset($order_local_cache);
        }
    }

    /**
     *生成订单轨迹记录,并将轨迹记录的表名保存到订单中
     * @param $data //订单轨迹缓存信息
     * @param $common_id
     * @return int|false
     * */
    public function createLocal($data,$common_id)
    {
        $local_model = new LocalModel();
        $local_table = $local_model->getLocalTable(array(),'id,table_name',false);
        $table_name = $local_table['table_name'];
        $count = $local_model->localCount($table_name,array());
        if($count>=config('intercity_local_max')){
            //生成新的数据表，保存轨迹
            $table_name = $this->createLocalTable($local_table);
        }
        $local_model->addLocalAll($table_name,$data);//保存该订单的轨迹信息
        $data_order_common['id'] = $common_id;
        $data_order_common['journey'] = $local_model->localOrderTrip($table_name,array('common_id'=>$common_id));
        $data_order_common['dis'] = $local_model->localOrderTrip($table_name,array('common_id'=>$common_id,'status'=>2));
        $data_order_common['local_table'] = $table_name;
        $order_model = new OrderCommonModel();
        $order_model->updateOrderCommon(array(),$data_order_common);//更新订单里程数
        return $data_order_common['journey'];
    }

    protected function createLocalTable($data)
    {
        $index = $data['id']+1;
        $table_name = substr_replace($data['table_name'],$index,strrpos($data['table_name'],'_')+1);
        $sql = "CREATE TABLE `{$table_name}` (
              `local_id` int(11) NOT NULL AUTO_INCREMENT,
              `driver_id` int(11) DEFAULT NULL COMMENT '司机id',
              `common_id` int(11) DEFAULT NULL COMMENT '订单id',
              `distance` int(11) DEFAULT NULL COMMENT '和上次坐标相比的距离差',
              `created_time` int(11) DEFAULT NULL COMMENT '记录时间',
              `longitude` varchar(255) DEFAULT NULL COMMENT '经度',
              `latitude` varchar(255) DEFAULT NULL COMMENT '纬度',
              `status` tinyint(1) DEFAULT NULL COMMENT '1:接单中(赶往乘客途中)\n2:送客中(订单有效进行中)',
              `direction` varchar(255) DEFAULT NULL COMMENT '方向',
              `speed` double DEFAULT NULL COMMENT '速度',
              PRIMARY KEY (`local_id`),
              KEY `did_sn` (`driver_id`,`common_id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1024 DEFAULT CHARSET=utf8 COMMENT='行程记录表{$index}';";
        Db::execute($sql);
        $local_model = new LocalModel();
        $local_model->addLocalTable(array('table_name'=>$table_name,'add_time'=>time()));
        return $table_name;
    }

    /**
     * 修改订单和司机关系缓存信息
     * @param $did
     * @param $common_id
     * @param $status//订单状态
     * @param $type //1为删除对应的$common_id缓存信息,2为更新缓存内容
     * */
    public function renewOrderDriverCache($did,$common_id,$status=35,$type=1)
    {
        /*---------------查询缓存，有无订单和司机关系记录-------------------------------------------------
        $order_driver_cache的形式为array('common_id1'=>'order_status1','common_id2'=>'order_status2',...)
        ------------------------------------------------------------------------------------------------*/
        $order_driver_cache = Cache::get('order_driver_' . $did);
        switch ($type){
            case 1:
                unset($order_driver_cache[$common_id]);
                break;
            case 2:
                $order_driver_cache[$common_id] = $status;
                break;
            default:
                break;
        }
        Cache::set('order_driver_' . $did,$order_driver_cache,86400);
        if(empty($order_driver_cache))Cache::rm('order_driver_' . $did);
    }

    /**
     * 获取乘客信息
     * @param $map
     * @param $field
     * @param $flag //true返回二维数组，false返回一维数组
     * @param $page
     * @param $limit
     * @return array|false
     **/
    public function getPassenger($map,$field='*',$flag = true,$page=1,$limit=10)
    {
        $passenger_model = new PassengerModel();
        return $passenger_model->getPassenger($map,$field,$flag,$page,$limit);
    }

    /**
     * 更新乘客信息
     * @param $map
     * @param $data
     * @return int|false
     * */
    public function renewPassenger($map=array(),$data)
    {
        if(empty($data)){
            return false;
        }
        $order_common = new PassengerModel();
        return $order_common->updatePassenger($map,$data);
    }

    /**
     * 生成乘客信息
     * @param $data
     * @return int|false
     * */
    public function createPassenger($data)
    {
        if(empty($data)){
            return false;
        }
        $order_common = new PassengerModel();
        return $order_common->addPassenger($data);
    }

}